package com.lmb.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ImageUtil {//图片上传工具类
    public static final String ENDPOINT="oss-cn-beijing.aliyuncs.com";//存储空间地址
    public static final String BUCKET_NAME="liminbao";//存储空间名称
    public static final String ACCESS_KEY_ID="LTAI5tHNtYyqiYFLVT7BXr9K" ;//阿里云账号
    public static final String ACCESS_KEY_SECRET="KQJzRgTr43hJsq9QQSaS626q2y3LOA";//阿里云密钥

    public static final OSS ossClient=new OSSClientBuilder().build("https://"+ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);//创建OSSClient实例
    public static String uploaad(InputStream is, String filename){
        String newFileName= UUID.randomUUID().toString()
                +filename.substring(filename.lastIndexOf("."));//生成新的文件名
        PutObjectRequest request=new PutObjectRequest(BUCKET_NAME,newFileName,is);//创建上传对象
        PutObjectResult result=ossClient.putObject(request);//上传文件
        return "https://"+BUCKET_NAME+"."+ENDPOINT+"/"+newFileName;//返回文件访问路径
    }

    public static List<String> getFilelist(){//获取文件列表
        List<String> list=new ArrayList<>();//创建文件列表
        ListObjectsRequest request=new ListObjectsRequest(BUCKET_NAME);//创建请求
        request.setMarker(null);//设置起始位置
        request.setMaxKeys(1000);//设置最大返回文件数
        ObjectListing objectListing=ossClient.listObjects(request);//获取文件列表
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()){
            list.add(objectSummary.getKey());
        }
        return list;
    }
    public static void delete(String filename){
        ossClient.deleteObject(BUCKET_NAME,filename);
    }
    public static void deleteList(List<String> fileNameList){
        DeleteObjectsRequest deleteObjectsRequest= new DeleteObjectsRequest(BUCKET_NAME);
        deleteObjectsRequest.setKeys(fileNameList);
        ossClient.deleteObjects(deleteObjectsRequest);
    }

    public static void main(String[] args) {
        System.out.println(getFilelist());

//        try {
//            File file=new File("E:\\uploadfile\\002.jpg");
//            InputStream is=new FileInputStream(file);
//            String newFileName = uploaad(is,file.getName());
//            System.out.println(newFileName);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

    }
}
